/**
 * jsbridge-sdk 获取WebViewJavascriptBridge,与Android设备进行交互
 */
;
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global.jssdk = factory());
})(this, function () {
  var __methods__ = []; // 调用Native的方法，通过jssdk调用
  var __clinets__ = []; // 存放客户端发来的请求方法

  //注册事件监听,判断bridge是否准备完毕
  function connectWebViewJavascriptBridge(callback) {
    if (window.WebViewJavascriptBridge) {
      callback(WebViewJavascriptBridge);
    } else {
      // 判断是__bridge否存在不存在则去加载。
      document.addEventListener('WebViewJavascriptBridgeReady', function (event) {
        if (window.onWebViewJavascriptBridgeReady) window.onWebViewJavascriptBridgeReady(window.__bridge =
          WebViewJavascriptBridge);
        callback(WebViewJavascriptBridge);
      }, false);
    }
  }

  /**
   * 获取类型
   * @param {Any} val 对象
   * @returns {String} 类型 
   */
  function getType(val) {
    var valTypeStr = Object.prototype.toString.call(val);
    return valTypeStr.slice(8, valTypeStr.length - 1);
  }

  /**
   * 构建方法
   * @param {Object} bridge 连接桥对象 
   * @param {Array} methods 方法列表
   * @param {Object} jssdk 调用方法 
   */
  function buildMethod(bridge, methods, jssdk) {
    methods = methods || [];
    var len = methods.length;
    if (len > 0){
        for (var i = 0; i < len; i++) {
          console.log('jssdk Method : [' + methods[i] + ']');
          jssdk[methods[i]] = (function (method) {
            return function (data, fn) {
              data = data || "";
              fn = fn || function () {};
              // 调用Native方法
              bridge.callHandler(
                method,
                data,
                fn
              );
            }
          })(methods[i]);
        }
    }
  }

  /**
   * 构建响应客户端的方法
   * @param {Object} bridge 连接桥对象 
   * @param {Array} clinets 方法列表
   * @param {Object} jssdk 调用方法 
   */
  function buildHandleClient(bridge, clinets, jssdk) {
    clinets = clinets || [];
    var len = clinets.length;
    if (len > 0){
        for (var i = 0; i < len; i++) {
          console.log('jssdk Client Method : [' + clinets[i] + ']');
          jssdk[clinets[i]] = (function (clinet) {
            return function (fn) {
              fn = fn || function () {};
              // 调用Native方法
              bridge.registerHandler(
                clinet,
                function (data, responseCallback) {
                  fn(data, responseCallback);
                }
              );
            }
          })(clinets[i]);
        }
    }

  }


  // 准备环境及相关的方法,必须先添加方法（addMethod,addClientMethod）
  var jssdk = {
    /**
     * 添加Native方法的调用
     * @param {Array | String} method
     */
    addMethod: function (method) {
      if (getType(method) === "String") {
        __methods__.push(method);
      }
      if (getType(method) === "Array") {
        for (var i = 0; i < method.length; i++) {
          __methods__.push(method[i]);
        }
      }
    },
    /**
     * 添加客户端响应的数据
     * @param {Array | String} method 
     */
    addClientMethod: function (method) {
      if (getType(method) === "String") {
        __clinets__.push(method);
      }
      if (getType(method) === "Array") {
        for (var i = 0; i < method.length; i++) {
          __clinets__.push(method[i]);
        }
      }
    },
    /**
     * 准备环境并添加方法
     * @param {Function} callback 
     */
    ready: function (callback) {
      var _this = this,
        ua = window.navigator.userAgent,
        ios = (/iPhone|iPad|iPod/ig).test(ua),
        android = (/Android/ig).test(ua);

        // 判断当前是否为移动设备
        if (!ios && !android){
          callback(jssdk);
        } else {
          connectWebViewJavascriptBridge(function (bridge) {
            // 构建处理客户端发来的请求
            buildHandleClient(bridge, __clinets__, jssdk);

            // 构建js向客户端发送请求的方法
            buildMethod(bridge, __methods__, jssdk);
            callback(jssdk);
          });
        }
    },
  }

  return jssdk;
});